from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import logging, json
from django.db.models.expressions import RawSQL
from geopy.distance import geodesic
from django.db.models import Q, Count, F
from django.http import JsonResponse
from urllib.parse import quote

from merchants.models import Merchant, MerchantBusinessQRCode, XYMSMerchant, XYMSMerchantImage
from orders.models import APIWhiteTable
from equity_mall.utils.utils import encrypt_CBC_pkcs7_padding, decrypt_CBC_pkcs7_padding, get_sign

ysh_merchant_logger = logging.getLogger('ysh_merchant')


class PostalLiveView(APIView):
    '''邮生活'''

    permission_classes = ()

    def post(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        contentModule = self.request.data.get('contentModule', '')
        pageSize = self.request.data.get('pageSize', '')
        longitude = self.request.data.get('longitude', '')
        latitude = self.request.data.get('latitude', '')
        subsource = self.request.data.get('subsource', '')
        ysh_merchant_logger.info(f'{ip}&contentModule={contentModule}&pageSize={pageSize}&longitude={longitude}&latitude={latitude}')
        ip_white_table = APIWhiteTable.objects.filter(char=ip, user_id=1)
        if not ip_white_table:
            return Response({'retCode': '其他', 'retMessage': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        if not contentModule:
            return Response({'retCode': '其他', 'retMessage': '请提交内容模块名称'}, status=status.HTTP_200_OK)
        if not pageSize:
            return Response({'retCode': '其他', 'retMessage': '请提交展示数量'}, status=status.HTTP_200_OK)
        if contentModule not in ['typeB', 'typeA', 'typeE', 'typeF', 'typeG', 'typeC', 'typeD', 'typeH', 'typeI', 'typeJ']:
            return Response({'retCode': '其他', 'retMessage': '内容模块名称有误'}, status=status.HTTP_200_OK)
        # if contentModule == 'typeA':
        #     return Response({'retCode': '其他', 'retMessage': '商户数据请求异常，错误提示：typeA'}, status=status.HTTP_200_OK)
        try:
            pageSize = int(pageSize)
        except:
            return Response({'retCode': '其他', 'retMessage': '展示数量格式有误,请提交正整数'}, status=status.HTTP_200_OK)
        if pageSize > 100:
            pageSize = 100
        if subsource == "XiaoYouMeiSu":
            queryset = XYMSMerchant.objects.filter(is_active=1, merchant_type__contains=contentModule)
            if contentModule == 'typeA':
                contentSubType = '美食'
            elif contentModule == 'typeB':
                contentSubType = '电影'
            elif contentModule == 'typeC':
                contentSubType = '出行'
            elif contentModule == 'typeD':
                contentSubType = '商超'
            elif contentModule == 'typeE':
                contentSubType = '外卖'
            elif contentModule == 'typeF':
                contentSubType = '旅游'
            elif contentModule == 'typeG':
                contentSubType = '住宿'
            elif contentModule == 'typeH':
                contentSubType = '医疗'
            elif contentModule == 'typeI':
                contentSubType = '娱乐'
            else:
                contentSubType = '更多'
            if latitude and longitude:
                try:
                    float(latitude)
                    float(longitude)
                except:
                    return Response({'retCode': '其他', 'retMessage': '经纬度格式有误'}, status=status.HTTP_200_OK)
                gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
                sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
                queryset = queryset.annotate(distance=sql).order_by(F('distance').asc(nulls_last=True))[:pageSize]
                response_data = {}
                response_data['retMessage'] = '查询成功'
                response_data['retCode'] = '1'
                lists = []
                for query in queryset:
                    merchant_data = {}
                    merchant_data['contentId'] = query.id
                    merchant_data['contentName'] = query.contentName
                    merchant_data['contentSubType'] = contentSubType
                    image_list = []
                    try:
                        image_set = XYMSMerchantImage.objects.filter(merchant_id=query.id)
                        for image in image_set:
                            image_list.append(image.image.url)
                        merchant_data['contentImgList'] = image_list
                    except:
                        merchant_data['contentImgList'] = []
                    merchant_data['contentLabelList'] = []
                    merchant_data['contentScore'] = query.contentScore
                    merchant_data['contentPrice'] = query.contentPrice
                    merchant_data['contentLink'] = {
                        "linkType": "MP",
                        "linkAppId": query.linkAppId,
                        "linkMpId": query.linkMpId,
                        "linkUrl": query.linkUrl,
                    }
                    try:
                        beginTime = query.beginTime
                        endTime = query.endTime
                    except:
                        beginTime = ''
                        endTime = ''
                    merchant_data['beginTime'] = beginTime
                    merchant_data['endTime'] = endTime
                    distance = geodesic((query.latitude, query.longitude), (latitude, longitude)).m
                    if distance > 1000:
                        merchant_data['distance'] = f'{round(distance/1000, 1)}km'
                    else:
                        merchant_data['distance'] = f'{int(distance)}m'
                    merchant_data['contentAddress'] = query.contentAddress
                    lists.append(merchant_data)
                response_data['data'] = lists
                return Response(response_data, status=status.HTTP_200_OK)
            else:
                queryset = queryset[:pageSize]
                response_data = {}
                response_data['retMessage'] = '查询成功'
                response_data['retCode'] = '1'
                lists = []
                for query in queryset:
                    merchant_data = {}
                    merchant_data['contentId'] = query.id
                    merchant_data['contentName'] = query.contentName
                    merchant_data['contentSubType'] = contentSubType
                    image_list = []
                    try:
                        image_set = XYMSMerchantImage.objects.filter(merchant_id=query.id)
                        for image in image_set:
                            image_list.append(image.image.url)
                        merchant_data['contentImgList'] = image_list
                    except:
                        merchant_data['contentImgList'] = []
                    merchant_data['contentLabelList'] = []
                    merchant_data['contentScore'] = query.contentScore
                    merchant_data['contentPrice'] = query.contentPrice
                    merchant_data['contentLink'] = {
                        "linkType": "MP",
                        "linkAppId": query.linkAppId,
                        "linkMpId": query.linkMpId,
                        "linkUrl": query.linkUrl,
                    }
                    try:
                        beginTime = query.beginTime
                        endTime = query.endTime
                    except:
                        beginTime = ''
                        endTime = ''
                    merchant_data['beginTime'] = beginTime
                    merchant_data['endTime'] = endTime
                    merchant_data['distance'] = f''
                    merchant_data['contentAddress'] = query.contentAddress
                    lists.append(merchant_data)
                response_data['data'] = lists
                return Response(response_data, status=status.HTTP_200_OK)
        else:
            queryset = Merchant.objects.filter(latitude__isnull=False).exclude(latitude='').distinct()
            if contentModule == 'typeA':
                queryset = queryset.filter(business_category_id=6)
                contentSubType = '美食'
            elif contentModule == 'typeB':
                queryset = queryset.filter(id=0)
                contentSubType = '电影'
            elif contentModule == 'typeC':
                queryset = queryset.filter(business_category_id__in=[4, 5])
                contentSubType = '出行'
            elif contentModule == 'typeD':
                queryset = queryset.filter(business_category_id__in=[2])
                contentSubType = '商超'
            elif contentModule == 'typeE':
                queryset = queryset.filter(id=0)
                contentSubType = '外卖'
            elif contentModule == 'typeF':
                queryset = queryset.filter(id=0)
                contentSubType = '旅游'
            elif contentModule == 'typeG':
                queryset = queryset.filter(id=0)
                contentSubType = '住宿'
            elif contentModule == 'typeH':
                queryset = queryset.filter(business_category_id__in=[9])
                contentSubType = '医疗'
            elif contentModule == 'typeI':
                queryset = queryset.filter(business_category_id__in=[7])
                contentSubType = '娱乐'
            else:
                queryset = queryset.exclude(business_category_id__in=[2,4,5,9,7,6])
                contentSubType = '更多'
            if latitude and longitude:
                try:
                    float(latitude)
                    float(longitude)
                except:
                    return Response({'retCode': '其他', 'retMessage': '经纬度格式有误'}, status=status.HTTP_200_OK)
                gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
                sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
                queryset = queryset.annotate(distance=sql).order_by(F('distance').asc(nulls_last=True))[:pageSize]
                response_data = {}
                response_data['retMessage'] = '查询成功'
                response_data['retCode'] = '1'
                lists = []
                for query in queryset:
                    qrcode = MerchantBusinessQRCode.objects.filter(merchant_id=query.id).first()
                    if qrcode:
                        key = f'/pages/sqm_active/sqm_active&id={qrcode.sn}'
                        # linkUrl = f'/pages/youzheng/youzheng?path=/pages/sqm_active/sqm_active&id={qrcode.sn}'
                    else:
                        key = f'/pages/store_detail/store_detail&id={query.id}'
                        # linkUrl = f'/pages/youzheng/youzheng?path=/pages/store_detail/store_detail&id={query.id}'
                    merchant_data = {}
                    merchant_data['contentId'] = query.id
                    merchant_data['contentName'] = query.name
                    merchant_data['contentSubType'] = contentSubType
                    try:
                        merchant_data['contentImgList'] = [query.store_header_copy.url]
                    except:
                        merchant_data['contentImgList'] = []
                    merchant_data['contentLabelList'] = []
                    merchant_data['contentScore'] = '4.0'
                    merchant_data['contentPrice'] = '50'
                    merchant_data['contentLink'] = {
                        "linkType": "MP",
                        "linkAppId": "wx950122ad80dc97c9",
                        "linkMpId": "gh_64d285f927c6",
                        "linkUrl": f'/pages/youzheng/youzheng?path={key}',
                    }
                    try:
                        beginTime = query.open_work_time.strftime("%H:%M")
                        endTime = query.close_work_time.strftime("%H:%M")
                    except:
                        beginTime = ''
                        endTime = ''
                    merchant_data['beginTime'] = beginTime
                    merchant_data['endTime'] = endTime
                    distance = geodesic((query.latitude, query.longitude), (latitude, longitude)).m
                    if distance > 1000:
                        merchant_data['distance'] = f'{round(distance/1000, 1)}km'
                    else:
                        merchant_data['distance'] = f'{int(distance)}m'
                    # merchant_data['distance'] = int(geodesic((query.latitude, query.longitude), (latitude, longitude)).m)
                    merchant_data['contentAddress'] = query.store_address
                    lists.append(merchant_data)
                response_data['data'] = lists
                return Response(response_data, status=status.HTTP_200_OK)
            else:
                queryset = queryset[:pageSize]
                response_data = {}
                response_data['retMessage'] = '查询成功'
                response_data['retCode'] = '1'
                lists = []
                for query in queryset:
                    qrcode = MerchantBusinessQRCode.objects.filter(merchant_id=query.id).first()
                    if qrcode:
                        key = f'/pages/sqm_active/sqm_active&id={qrcode.sn}'
                        # linkUrl = f'/pages/youzheng/youzheng?path=/pages/sqm_active/sqm_active&id={qrcode.sn}'
                    else:
                        key = f'/pages/store_detail/store_detail&id={query.id}'
                        # linkUrl = f'/pages/youzheng/youzheng?path=/pages/store_detail/store_detail&id={query.id}'
                    merchant_data = {}
                    merchant_data['contentId'] = query.id
                    merchant_data['contentName'] = query.name
                    merchant_data['contentSubType'] = contentSubType
                    try:
                        merchant_data['contentImgList'] = [query.store_header_copy.url]
                    except:
                        merchant_data['contentImgList'] = []
                    merchant_data['contentLabelList'] = []
                    merchant_data['contentScore'] = '4.0'
                    merchant_data['contentPrice'] = '50'
                    merchant_data['contentLink'] = {
                        "linkType": "MP",
                        "linkAppId": "wx950122ad80dc97c9",
                        "linkMpId": "gh_64d285f927c6",
                        "linkUrl": f'/pages/youzheng/youzheng?path={key}',
                    }
                    try:
                        beginTime = query.open_work_time.strftime("%H:%M")
                        endTime = query.close_work_time.strftime("%H:%M")
                    except:
                        beginTime = ''
                        endTime = ''
                    merchant_data['beginTime'] = beginTime
                    merchant_data['endTime'] = endTime
                    merchant_data['distance'] = ''
                    merchant_data['contentAddress'] = query.store_address
                    lists.append(merchant_data)
                response_data['data'] = lists
                return Response(response_data, status=status.HTTP_200_OK)


class PostalLiveView1(APIView):
    '''邮生活'''

    permission_classes = ()

    def post(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        ip_white_table = APIWhiteTable.objects.filter(char=ip, user_id=1)
        if not ip_white_table:
            return Response({'retCode': '其他', 'retMessage': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        response_data = {
                        "retCode": "1",
                        "retMessage": "查询成功",
                        "data": {
                            "typeList": [
                                {
                                    "paramName": "美食",
                                    "paramCode": "typeA"
                                },
                                {
                                    "paramName": "出行",
                                    "paramCode": "typeC"
                                },
                                {
                                    "paramName": "商超",
                                    "paramCode": "typeD"
                                },
                                {
                                    "paramName": "医疗",
                                    "paramCode": "typeH"
                                },
                                {
                                    "paramName": "娱乐",
                                    "paramCode": "typeI"
                                },
                                {
                                    "paramName": "住宿",
                                    "paramCode": "typeG"
                                },
                                {
                                    "paramName": "更多",
                                    "paramCode": "typeJ"
                                }

                            ],
                            "subsourceList": [
                                {
                                    "paramName": "微邮惠",
                                    "paramCode": "WeiYouHui"
                                },
                                {
                                    "paramName": "小邮美宿",
                                    "paramCode": "XiaoYouMeiSu"
                                }
                            ]
                        }
                    }
        return Response(response_data, status=status.HTTP_200_OK)


